package cn.hnu.qq.server.thread;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.sound.midi.SysexMessage;

import cn.hnu.qq.entity.Crowd;
import cn.hnu.qq.entity.User;
import cn.hnu.qq.entity.message.CrowdInfoMessage;
import cn.hnu.qq.entity.message.IpInfoMessage;
import cn.hnu.qq.entity.message.LogonMessage;
import cn.hnu.qq.entity.message.LogonSuccessMessage;
import cn.hnu.qq.entity.message.Message;
import cn.hnu.qq.entity.message.OnlineMessage;
import cn.hnu.qq.entity.message.QueryCrowdInfoMessage;
import cn.hnu.qq.entity.message.QueryIPInfoMessage;

public class ClientServerThread extends AbstractClientThread implements Runnable {

	
	public ClientServerThread(Socket s) {
		super(s);
	}

	public void run() {
		System.out.println("进入 ClientServerThread run");
		while(true){
			try {
				//TODO 处理input output堵塞
				getOutput();//处理input output堵塞
				Message message = (Message) getInput().readObject();
				System.out.println("进入 ClientServerThread run 读取对象");
				switch(message.getMessageType()){
				case LOGON:
					handleLogon((LogonMessage)message);
					break;
				case QUERY_IP_INFO:
					handleQueryIpInfo((QueryIPInfoMessage) message);
					break;
				case QUERY_CROWD_INFO:
					handleQueryCrowdInfo((QueryCrowdInfoMessage)message);
					break;
				}
			} catch (Exception e) {
				System.err.println("ClientServerThread对象读取失败");
				e.printStackTrace();
			}			
		}
	}

	private void handleQueryCrowdInfo(QueryCrowdInfoMessage message) throws Exception {
		Integer crowdId = message.getCrowdId();
		Crowd crowd = getCrowdDao().findById(crowdId);
		Map<String,User> users = new HashMap<String,User>();
		Set<User> _users = crowd.getUsers();
		for(User u :_users){
			if(userinfos.get(u.getAcount()) != null){
				User _user = userinfos.get(u.getAcount());
				users.put(_user.getAcount(), _user);
			}
		}
		CrowdInfoMessage cim = new CrowdInfoMessage();
		cim.setUsers(users);
		getOutput().writeObject(cim);
		getOutput().flush();
	}

	private void handleQueryIpInfo(QueryIPInfoMessage message) throws Exception {
		String account = message.getAccount();
		User user = null;
		if((user = isUserOnline(account)) == null){
			//TODO 处理用户不在线的情况
		}else{
			IpInfoMessage mes = new IpInfoMessage();
			mes.setAccount(account);
			mes.setIpAddr(user.getIp());
			mes.setClientListenPort(userinfos.get(account).getUserClientPort());
			getOutput().writeObject(mes);
			getOutput().flush();
		}
		
	}

	private void handleLogon(LogonMessage message) throws Exception {
		User user = getUserDao().findByAcount(message.getUserName());
		
		if(user.getPassword().equals(message.getPassword())){
			LogonSuccessMessage ms = new LogonSuccessMessage();
			user.setUserClientPort(message.getClientListenPort()); //设置客户端监听端口
			//TODO  通知在线好友 我上线啦
			Set<User> users = user.getFriends();
			for(User u:users){
				User _user = isUserOnline(u.getAcount());
				if(_user != null){
					//告知该地址用户 我上线啦
					OnlineMessage om = new OnlineMessage();
					om.setAccount(user.getAcount());
					om.setIpAddr(getSocket().getInetAddress().getHostAddress());
					om.setPort(message.getClientListenPort());
					ClientServerThread cst = ListenThread.getInstance().getClientServerThread(_user.getAcount());
					if(cst != null){
						System.err.println("发送在线消息");
						cst.sendOnlineMessage(om);
					}
				}
			}
			user.setIp(getSocket().getInetAddress().getHostAddress());
			ms.setUser(user);
			System.out.println(user);
			userinfos.put(user.getAcount(), user);
			getOutput().writeObject(ms);
			getOutput().flush();
			ListenThread.getInstance().petClientServerThread(user.getAcount(),this);
		}
	}

	private void sendOnlineMessage(OnlineMessage om) throws Exception {
		getOutput().writeObject(om);
		getOutput().flush();
	}
	
	
}
